package mspbots.autotask.data.core.inventoryitems;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class InventoryItemsReceiver {

    private final InventoryItemsRepository inventoryItemsRepository;

//    @RabbitListener(queues = "auto-task.inventory-items.sync")
    public void syncTask(ResultMsg content) {
        InventoryItem inventoryItem = InventoryItem.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();


        this.inventoryItemsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    inventoryItem.setId(ticket.getId());
                    return inventoryItem;
                })
                .defaultIfEmpty(inventoryItem)
                .flatMap(this.inventoryItemsRepository::save)
                .block(Duration.ofSeconds(10));
    }
}
